package cn.wolfcode.listener;

import cn.wolfcode.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.cache.vo.StrategyStatisVO;
import cn.wolfcode.domain.Strategy;
import cn.wolfcode.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;
//redis数据初始化监听器

//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    // 当容器调用 refresh() 方法时马上执行下面的逻辑   spring容器启动后,并初始化完成后马上执行下面的逻辑
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("-----------初始化 vo start----------");

        //为防止每次更新覆盖  如果redis已经存在vo对象  直接跳过
        //查询mongodb 中所有的攻略
        List<Strategy> list = strategyService.findAll();
        //将攻略对象转换成vo对象
        for (Strategy st : list) {
            //判断对象是否在redis中
            if(strategyStatisVORedisService.isStrategyVoExists(st.getId())){
                continue;
            }

            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(st, vo);
            vo.setStrategyId(st.getId());
            //将vo对象缓存到redis中
            strategyStatisVORedisService.setStrategyStatisVo(vo);
        }


    }
}
